#!/usr/bin/env python3
import argparse
from rich.console import Console
from rich.syntax import Syntax
from rich.table import Table
import sys
import os

console = Console()

# 自定义脚本语言的执行器类
class BipScriptExecutor:
    def __init__(self, filename):
        self.filename = filename
        self.variables = {}
        self.functions = {}

    def execute(self, debug=False):
        """执行 .bip 脚本文件"""
        if not os.path.exists(self.filename):
            console.print(f"[red]错误: 文件 {self.filename} 不存在[/red]")
            return False

        with open(self.filename, 'r', encoding='utf-8') as f:
            lines = f.readlines()

        line_number = 0
        for line in lines:
            line_number += 1
            line = line.strip()
            if not line or line.startswith('#'):
                continue

            try:
                self.parse_line(line, debug, line_number)
            except Exception as e:
                console.print(f"[red]错误在行 {line_number}: {str(e)}[/red]")
                return False
        return True

    def parse_line(self, line, debug, line_number):
        """解析并执行单行命令"""
        parts = line.split()
        if not parts:
            return

        command = parts[0].lower()

        # 基本命令集
        if command == "print":
            self.cmd_print(" ".join(parts[1:]))
        elif command == "var":
            self.cmd_variable(parts[1:])
        elif command == "if":
            self.cmd_if(" ".join(parts[1:]))
        elif command == "func":
            self.cmd_function(parts[1:], line_number)
        elif command == "call":
            self.cmd_call(parts[1:])
        elif command == "loop":
            self.cmd_loop(parts[1:])
        else:
            console.print(f"[yellow]警告: 未知命令 '{command}' 在行 {line_number}[/yellow]")

        if debug:
            console.print(f"[cyan]调试: 执行 '{line}' 在行 {line_number}[/cyan]")

    def cmd_print(self, text):
        """打印命令"""
        if text.startswith('$'):
            var_name = text[1:]
            value = self.variables.get(var_name, "未定义变量")
            console.print(f"[green]{value}[/green]")
        else:
            console.print(f"[green]{text}[/green]")

    def cmd_variable(self, args):
        """变量赋值"""
        if len(args) < 2 or args[1] != '=':
            raise ValueError("变量语法错误: 需要 var name = value")
        name = args[0]
        value = " ".join(args[2:])
        self.variables[name] = value

    def cmd_if(self, condition):
        """简单条件判断"""
        parts = condition.split()
        if len(parts) < 3:
            raise ValueError("if 语法错误: 需要 if var == value")
        var, op, val = parts[0], parts[1], parts[2]
        if var.startswith('$'):
            var_value = self.variables.get(var[1:], "")
            if op == "==" and var_value == val:
                console.print("[blue]条件为真[/blue]")
            else:
                console.print("[blue]条件为假[/blue]")

    def cmd_function(self, args, line_number):
        """定义函数"""
        if len(args) < 1:
            raise ValueError("func 语法错误: 需要 func name")
        name = args[0]
        self.functions[name] = line_number

    def cmd_call(self, args):
        """调用函数"""
        if len(args) < 1:
            raise ValueError("call 语法错误: 需要 call name")
        func_name = args[0]
        if func_name not in self.functions:
            raise ValueError(f"未定义的函数: {func_name}")

    def cmd_loop(self, args):
        """简单循环"""
        if len(args) < 1:
            raise ValueError("loop 语法错误: 需要 loop times")
        try:
            times = int(args[0])
            for i in range(times):
                console.print(f"[purple]循环 {i+1}/{times}[/purple]")
        except ValueError:
            raise ValueError("loop 参数必须是数字")

def main():
    # 命令行参数解析
    parser = argparse.ArgumentParser(
        description="Bip Script Executor - 自定义脚本语言执行器",
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("script", help="要执行的 .bip 脚本文件")
    parser.add_argument("-d", "--debug", action="store_true", help="启用调试模式")
    parser.add_argument("-v", "--verbose", action="store_true", help="显示详细信息")
    parser.add_argument("-o", "--output", help="指定输出文件")
    args = parser.parse_args()

    # 检查文件扩展名
    if not args.script.endswith('.bip'):
        console.print("[red]错误: 文件必须以 .bip 结尾[/red]")
        sys.exit(1)

    # 创建执行器实例
    executor = BipScriptExecutor(args.script)

    # 重定向输出（如果指定）
    if args.output:
        sys.stdout = open(args.output, 'w', encoding='utf-8')

    # 执行脚本
    console.print(f"[bold cyan]开始执行脚本: {args.script}[/bold cyan]")
    success = executor.execute(debug=args.debug)

    # 显示变量状态（如果启用详细模式）
    if args.verbose and executor.variables:
        table = Table(title="变量状态")
        table.add_column("名称", style="cyan")
        table.add_column("值", style="green")
        for name, value in executor.variables.items():
            table.add_row(name, value)
        console.print(table)

    # 结束信息
    if success:
        console.print("[bold green]脚本执行成功[/bold green]")
    else:
        console.print("[bold red]脚本执行失败[/bold red]")
        sys.exit(1)

if __name__ == "__main__":
    main()